/**
 * 
 */
package web.util;

/**
 *  密码加密算法实用类。
 *  包括两种算法，第一种简单的右移5位，第二种依赖KEY，随机数动态生成
 * 
 * @author 陈瑞军
 */
public class PasswordEnCryptor {
	
	private static String KEY = "CHENCY";
	
	private static final int OFF = 5;

	public static String simpleEncrypt(String password) {
		if (null == password || password.equals(""))
			return null;
		StringBuffer result = new StringBuffer("");
		CharSequence charSequence = password.subSequence(0, password.length());
		for (int i = 0; i < charSequence.length(); i++) {
			result.append((char)((int)charSequence.charAt(i) + OFF));
		}
		return result.toString();
	}
	
	public static String simpleDecrypt(String password) {
		if (null == password || password.equals(""))
			return null;
		StringBuffer result = new StringBuffer("");
		CharSequence charSequence = password.subSequence(0, password.length());
		for (int i = 0; i < charSequence.length(); i++) {
			result.append((char)((int)charSequence.charAt(i) - OFF));
		}
		return result.toString();
	}

	public static String encrypt(String password) {
		if (null == password || password.equals(""))
			return null;
		int random = (int)(Math.random()*256);
		String dest = Integer.toHexString(random);
		if (dest.length() == 1) {
			dest = "0" + dest;
		}
		CharSequence charSequence = password.subSequence(0, password.length());
		
		// key³¤¶È
		int keyLen = KEY.length();
		int keyPos = -1;
		
		for (int i = 0; i < charSequence.length(); i++) {
			int nextRandom = ((int)charSequence.charAt(i) + random) % 255;
			if (keyPos++ >= keyLen - 1)
				keyPos = 0;  // µ½´ï³¤¶Èºó£¬³õÊ¼»¯1
			random = nextRandom ^ KEY.charAt(keyPos);
			String temp = Integer.toHexString(random);
			if (temp.length() == 1) {
				temp = "0" + temp;
			}
			dest = dest + temp;
		}
		return dest;
	}
	
	public static String decrypt(String password) {
		if (null == password || password.equals(""))
			return null;
		int keyPos = 0;
		String[] srcAr = new String[password.length() / 2];
		for (int i = 0; i < password.length(); i= i + 2) {
			srcAr[i / 2] = password.substring(i, i + 2);
		}
		int random = Integer.parseInt(srcAr[0], 16);
		StringBuffer sb = new StringBuffer("");
		for (int i = 1; i < srcAr.length; i++) {
			int temp = Integer.parseInt(srcAr[i], 16) ^ KEY.charAt(keyPos);
			char t = (char)((temp - random) > 0 ? (temp - random) : (temp - random + 255));
			sb.append(t);
			int nextRandom = (((int)t + random) % 255) ^ KEY.charAt(keyPos);
			if (keyPos++ >= KEY.length() - 1)
				keyPos = 0;  
			random = nextRandom;
		}
		return sb.toString();
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(PasswordEnCryptor.decrypt("7AB35CAC63F0202B23270855"));
	}
}
